package com.neko.Thread_Learning.t16_No_synchronized_Demo;


/**
 * 16、非线程安全【错误示范】
 * --------------------------
 *  1、没有加 Lock / synchronized == 【 没有排队 】
 *      会导致 同时抢夺资源（多核心CPU，幻读，幻写）
 *
 * */
public class UnSafeBuyTicket {

    public static void main(String[] args) {

        BuyTicket buyTicket = new BuyTicket();

        new Thread(buyTicket, "苦逼的我").start();
        new Thread(buyTicket, "牛逼的你们").start();
        new Thread(buyTicket, "可恶的黄牛党").start();

    }
}

class BuyTicket implements Runnable {

    private int ticketNums = 10;
    private boolean flag = true;

    @Override
    public void run() {
        // 买票
        while (flag) {
            try {
                buy();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 安全线程 写法 + synchronized
     *      锁住 this -> 锁定 method の 调用者 == this
     * */
//    private synchronized void buy() throws InterruptedException {
    private void buy() throws InterruptedException {
        // 判断是否有票
        if (ticketNums <= 0) {
            flag = false;
            return ;
        }

        // 模拟延时
        Thread.sleep(100);

        // 买票
        System.out.println(Thread.currentThread().getName() + " 拿到 " + ticketNums--);
    }


}


